package svgedit.gui.actions;

import java.io.File;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

import svgedit.gui.Frame;
import svgedit.gui.SVGFileFilter;
import svgedit.xml.XMLWriter;

public class SaveAsUtil {
	
	JFileChooser fc;
	XMLWriter writer = new XMLWriter();

	public SaveAsUtil()
	{
		fc = new JFileChooser();
        fc.addChoosableFileFilter(new SVGFileFilter());
	}
	/**
	 * Saves the user drawings to a SVG file with user defined file name and location
	 * @param frame
	 */
	public void SaveAs(Frame frame)
	{
		int actionDialog = fc.showSaveDialog(null);
	    if (actionDialog == JFileChooser.APPROVE_OPTION) {
	        File file = fc.getSelectedFile();
	        file = new File(file.getAbsolutePath()+".svg");
	        if(file != null)
	        {
	        	//Checks to see if the file already excists. 
	            if(file.exists())
	            {
	                actionDialog = JOptionPane.showConfirmDialog(null, "Replace existing file?");
	                while (actionDialog == JOptionPane.NO_OPTION)
	                {
	                    actionDialog=fc.showSaveDialog(null);
	                    if (actionDialog == JFileChooser.APPROVE_OPTION)
	                    {
	                    	file = fc.getSelectedFile();
	                    	file = new File(file.getAbsolutePath()+".svg");
	                        if(file.exists())
	                        {
	                            actionDialog = JOptionPane.showConfirmDialog(null, "Replace existing file?");
	                        }
	                    }
	                }
	                if(actionDialog == JOptionPane.YES_OPTION)
	                {
	                    try {
	                    	writer.write(file, frame);
	                    	frame.view.setSaveState(0);
	        			} catch (Exception e1) {
	        				e1.printStackTrace();
	        			}
	                }
	                return;
	            }
	            try {
	            	writer.write(file, frame);
	            	frame.view.setSaveState(0);
				} catch (Exception e1) {
					e1.printStackTrace();
				}
	        }        
	    } 
	    else {
	    }
	}
}
